package com.wanka.jutou;

import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Optional;

/**
 * @author yangqing
 * @version 1.0
 * @date 2025/9/1 17:13
 * @description
 */
public enum RuleType {
    FLOW("flow", FlowRule.class),
    DEGRADE("degrade", DegradeRule.class),
    PARAM_FLOW("param-flow", ParamFlowRule.class),
    SYSTEM("system", SystemRule.class),
    AUTHORITY("authority", AuthorityRule.class),
    GW_FLOW("gw-flow", "com.wanka.jutou.gateway.rule.GatewayFlowRule"),
    GW_API_GROUP("gw-api-group", "com.wanka.jutou.gateway.api.ApiDefinition");

    private final String name;
    private Class clazz;
    private String clazzName;

    private RuleType(String name, Class clazz) {
        this.name = name;
        this.clazz = clazz;
    }

    private RuleType(String name, String clazzName) {
        this.name = name;
        this.clazzName = clazzName;
    }

    public String getName() {
        return this.name;
    }

    public Class getClazz() {
        if (this.clazz != null) {
            return this.clazz;
        } else {
            try {
                return Class.forName(this.clazzName);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static Optional<RuleType> getByName(String name) {
        return StringUtils.isEmpty(name) ? Optional.empty() : Arrays.stream(values()).filter((ruleType) -> name.equals(ruleType.getName())).findFirst();
    }

    public static Optional<RuleType> getByClass(Class clazz) {
        return Arrays.stream(values()).filter((ruleType) -> clazz == ruleType.getClazz()).findFirst();
    }
}
